package com.chengyu.core.service.ty.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.NumberUtil;
import com.alipay.api.domain.OrderDetail;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.chengyu.core.domain.CommonConstant;
import com.chengyu.core.domain.enums.OrderEnums;
import com.chengyu.core.domain.form.OrderCommentForm;
import com.chengyu.core.domain.form.OrderCommentSearchForm;
import com.chengyu.core.domain.result.OrderCommentResult;
import com.chengyu.core.domain.result.TyOrderCommentResult;
import com.chengyu.core.entity.CommonPage;
import com.chengyu.core.exception.ServiceException;
import com.chengyu.core.mapper.*;
import com.chengyu.core.model.*;
import com.chengyu.core.service.order.OrderCommentService;
import com.chengyu.core.service.ty.TyOrderCommentService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

@Slf4j
@Service
public class TyOrderCommentServiceImpl implements TyOrderCommentService {

	@Autowired
	private TyOrderCommentMapper orderCommentMapper;
	@Autowired
	private BaseMapper baseMapper;
	@Autowired
	private TyOrderMapper orderMapper;
	@Autowired
	private TyOrderCommentLeftMapper orderCommentLeftMapper;


	@Override
	public List<TyOrderComment> getCommentList(OrderCommentSearchForm form, Integer page, Integer pageSize) {
		PageHelper.startPage(page, pageSize);

		TyOrderCommentExample example = new TyOrderCommentExample();
		example.setOrderByClause("add_time desc");
		TyOrderCommentExample.Criteria criteria = example.createCriteria();
		if(form.getOrderId() != null){
			TyOrderExample detailExample = new TyOrderExample();
			detailExample.createCriteria().andIdEqualTo(form.getOrderId());
			List<TyOrder> detailList = orderMapper.selectByExample(detailExample);
			criteria.andDetailIdIn(detailList.stream().map(TyOrder::getId).collect(Collectors.toList()));
		}
		if(form.getGoodsId() != null){
			criteria.andGoodsIdEqualTo(form.getGoodsId());
		}
		if(form.getDetailId() != null){
			criteria.andDetailIdEqualTo(form.getDetailId());
		}
		if(form.getMemberId() != null){
			criteria.andMemberIdEqualTo(form.getMemberId());
		}
		if(form.getStatus() != null){
			criteria.andStatusEqualTo(form.getStatus());
		}
		if(CollectionUtil.isNotEmpty(form.getStatusList())){
			criteria.andStatusIn(form.getStatusList());
		}
		if(form.getShopId() != null){
			criteria.andShopIdEqualTo(form.getShopId());
		}
		if(form.getGoodsComment() != null){
			if(form.getGoodsComment() == 4){
				//有图
				criteria.andImgIsNotNull();
			}else{
				criteria.andGoodsCommentEqualTo(form.getGoodsComment());
			}
		}
		return orderCommentMapper.selectByExample(example);
	}

	@Override
	public CommonPage<OrderCommentResult> getCommentListByGoods(OrderCommentSearchForm form, Integer page, Integer pageSize) {
		List<TyOrderComment> list = this.getCommentList(form, page, pageSize);
		List<TyOrderCommentResult> commenList = new ArrayList<>();
		for(TyOrderComment comment : list){
			TyOrderCommentResult result = new TyOrderCommentResult();
			result.setComment(comment);

			TyOrderCommentLeftExample commentLeftExample = new TyOrderCommentLeftExample();
			commentLeftExample.setOrderByClause("add_time asc");
			commentLeftExample.createCriteria().andCommentIdEqualTo(comment.getId());
			result.setLeftCommentList(orderCommentLeftMapper.selectByExample(commentLeftExample));
			commenList.add(result);
		}

		PageInfo pageInfo = new PageInfo<>(list);
		pageInfo.setList(commenList);
		return CommonPage.restPage(pageInfo);
	}

	@Override
	@Transactional(propagation=Propagation.REQUIRED, rollbackFor=Exception.class)
	public void initComment(List<TyOrder> detailList) {
		Date now = DateUtil.date();
		for(TyOrder detail : detailList){
			TyOrderComment comment = new TyOrderComment();
			comment.setOrderId(detail.getId());
//			comment.setGoodsId(detail.getGoodsId());
//			comment.setGoodsName(detail.getGoodsName());
//			comment.setGoodsMainImg(detail.getGoodsMainImg());
//			comment.setGoodsParamName(detail.getGoodsParamName());
			comment.setShopId(detail.getShopId());
			comment.setShopName(detail.getShopName());
//			comment.setMemberId(detail.getMemberId());
			comment.setMemberId(detail.getMerMemberId());

			comment.setMemberName(detail.getMemberName());
			comment.setMemberHeadImg(detail.getMemberHeadImg());
			comment.setStatus(OrderEnums.CommentStatus.WAIT_COMMENT.getValue());
			comment.setAddTime(now);
			comment.setUpdTime(now);
			orderCommentMapper.insertSelective(comment);
		}
	}

	@Override
	@Transactional(propagation=Propagation.REQUIRED, rollbackFor=Exception.class)
	public void addComment(UmsMember member, OrderCommentForm form) throws ServiceException {
//		TyOrderComment comment;
//		if(form.getId() != null){
//			comment = orderCommentMapper.selectByPrimaryKey(form.getId());
//		}else{
//			TyOrderCommentExample example = new TyOrderCommentExample();
//			example.createCriteria().andDetailIdEqualTo(form.getDetailId());
//			List<TyOrderComment> commentList = orderCommentMapper.selectByExample(example);
//			comment = CollectionUtil.isEmpty(commentList) ? null : commentList.get(0);
//		}
//		if(comment == null || comment.getStatus() != OrderEnums.CommentStatus.WAIT_COMMENT.getValue()){
//			throw new ServiceException("order.comment.add");
//		}
//		this.comment(comment, form)


		TyOrder order;
		if(form.getId() != null){
			order  = orderMapper.selectByPrimaryKey(form.getId());
		}else{
			throw new ServiceException("order.comment.add");
		}

		if(order == null || order.getCommentStatus() != OrderEnums.CommentStatus.WAIT_COMMENT.getValue()){
			throw new ServiceException("order.comment.add");
		}
		this.comment( order ,form,member);


	}

	private void comment(TyOrder order, OrderCommentForm form,UmsMember member){
		TyOrderComment updateComment = new TyOrderComment();
//		updateComment.setId(order.getId());
		updateComment.setOrderId(form.getId());
//		updateComment.setType("ty");
		updateComment.setMemberId(order.getMemberId());

		updateComment.setMemberName(member.getNickname());
		updateComment.setMemberHeadImg(member.getHeadImg());


		updateComment.setAnonymousStatus(form.getAnonymousStatus());
		updateComment.setContent(form.getContent());
		updateComment.setImg(form.getImg());
		updateComment.setGoodsComment(form.getGoodsComment());
		updateComment.setGoodsStarNum(form.getGoodsStarNum());
		updateComment.setDeliveryStarNum(form.getDeliveryStarNum());
		updateComment.setShopStarNum(form.getShopStarNum());
		updateComment.setLogisticStarNum(form.getLogisticStarNum());
		updateComment.setAvgStarNum(NumberUtil.div(NumberUtil.add(form.getGoodsStarNum(), form.getDeliveryStarNum(), form.getShopStarNum(),form.getLogisticStarNum()), 4));
		updateComment.setStatus(OrderEnums.CommentStatus.COMMENTED.getValue());
		updateComment.setUpdTime(DateUtil.date());
		orderCommentMapper.insertSelective(updateComment);

		//更新订单详情页面的评价状态
		TyOrder updateDetail = new TyOrder();
		updateDetail.setId(order.getId());
		updateDetail.setCommentStatus(1);
		orderMapper.updateByPrimaryKeySelective(updateDetail);

		//更新商品评价的数量
		StringBuilder updateSql = new StringBuilder();
		updateSql.append("update pms_goods set comment_num = comment_num+1");
		if(form.getGoodsComment() == OrderEnums.CommentType.GOOD.getValue()){
			updateSql.append(" ,good_comment_num=good_comment_num+1 ");
		}else if(form.getGoodsComment() == OrderEnums.CommentType.BAD.getValue()){
			updateSql.append(" ,bad_comment_num=bad_comment_num+1 ");
		}
		updateSql.append(" where id="+order.getId());
		baseMapper.update(updateSql.toString());

		//更新店铺的评分
	}

	private void comment(TyOrderComment comment, OrderCommentForm form){
		TyOrderComment updateComment = new TyOrderComment();
		updateComment.setId(comment.getId());
		updateComment.setOrderId(comment.getId());
		updateComment.setAnonymousStatus(form.getAnonymousStatus());
		updateComment.setContent(form.getContent());
		updateComment.setImg(form.getImg());
		updateComment.setGoodsComment(form.getGoodsComment());
		updateComment.setGoodsStarNum(form.getGoodsStarNum());
		updateComment.setDeliveryStarNum(form.getDeliveryStarNum());
		updateComment.setShopStarNum(form.getShopStarNum());
		updateComment.setLogisticStarNum(form.getLogisticStarNum());
		updateComment.setAvgStarNum(NumberUtil.div(NumberUtil.add(form.getGoodsStarNum(), form.getDeliveryStarNum(), form.getShopStarNum(),form.getLogisticStarNum()), 4));
		updateComment.setStatus(OrderEnums.CommentStatus.COMMENTED.getValue());
		updateComment.setUpdTime(DateUtil.date());
		orderCommentMapper.updateByPrimaryKeySelective(updateComment);

		//更新订单详情页面的评价状态
		TyOrder updateDetail = new TyOrder();
		updateDetail.setId(form.getId());
		updateDetail.setCommentStatus(1);
		orderMapper.updateByPrimaryKeySelective(updateDetail);

		//更新商品评价的数量
		StringBuilder updateSql = new StringBuilder();
		updateSql.append("update pms_goods set comment_num = comment_num+1");
		if(form.getGoodsComment() == OrderEnums.CommentType.GOOD.getValue()){
			updateSql.append(" ,good_comment_num=good_comment_num+1 ");
		}else if(form.getGoodsComment() == OrderEnums.CommentType.BAD.getValue()){
			updateSql.append(" ,bad_comment_num=bad_comment_num+1 ");
		}
		updateSql.append(" where id="+comment.getGoodsId());
		baseMapper.update(updateSql.toString());

		//更新店铺的评分
	}

	@Override
	@Transactional(propagation=Propagation.REQUIRED, rollbackFor=Exception.class)
	public void updateComment(TyOrderComment comment) {
		comment.setUpdTime(DateUtil.date());
		orderCommentMapper.updateByPrimaryKey(comment);
	}

	@Override
	@Transactional(propagation=Propagation.REQUIRED, rollbackFor=Exception.class)
	public void deleteComment(Integer commentId) {
		orderCommentMapper.deleteByPrimaryKey(commentId);

		TyOrderCommentLeftExample example = new TyOrderCommentLeftExample();
		example.createCriteria().andCommentIdEqualTo(commentId);
		orderCommentLeftMapper.deleteByExample(example);
	}

	@Override
	@Transactional(propagation=Propagation.REQUIRED, rollbackFor=Exception.class)
	public void autoComment(String orderNo) {
		TyOrderExample example = new TyOrderExample();
		example.createCriteria().andOrderNoEqualTo(orderNo);
		List<TyOrder> detailList = orderMapper.selectByExample(example);

		if(CollectionUtil.isNotEmpty(detailList)){
			TyOrderCommentExample commentExample = new TyOrderCommentExample();
			commentExample.createCriteria().andDetailIdIn(detailList.stream().map(TyOrder::getId).collect(Collectors.toList()))
					.andStatusEqualTo(OrderEnums.CommentStatus.WAIT_COMMENT.getValue());
			List<TyOrderComment> commentList = orderCommentMapper.selectByExample(commentExample);
			if(CollectionUtil.isNotEmpty(commentList)){
				//自动评价
				for(TyOrderComment comment : commentList){
					OrderCommentForm form = new OrderCommentForm();
					form.setAnonymousStatus(CommonConstant.YES_INT);
					form.setContent("评价方未及时做出评价,系统默认好评!");
					form.setGoodsComment(OrderEnums.CommentType.GOOD.getValue());
					BigDecimal good = new BigDecimal(5);
					form.setGoodsStarNum(good);
					form.setDeliveryStarNum(good);
					form.setShopStarNum(good);
					form.setLogisticStarNum(good);
					this.comment(comment, form);
				}
			}
		}
	}

	@Override
	public List<TyOrderCommentLeft> getLeftCommentList(Integer commentId) {
		TyOrderCommentLeftExample example = new TyOrderCommentLeftExample();
		example.setOrderByClause("add_time desc");
		example.createCriteria().andCommentIdEqualTo(commentId);
		return orderCommentLeftMapper.selectByExample(example);
	}

	@Override
	@Transactional(propagation=Propagation.REQUIRED, rollbackFor=Exception.class)
	public void addLeftComment(UmsMember member, Integer commentId, Integer type, String content, String img) {
		TyOrderCommentLeft commentLeft = new TyOrderCommentLeft();
		commentLeft.setCommentId(commentId);
		commentLeft.setType(type);
		commentLeft.setContent(content);
		commentLeft.setImg(img);
		commentLeft.setMemberId(member.getId());
		commentLeft.setMemberName(member.getNickname());
		commentLeft.setMemberHeadImg(member.getHeadImg());
		commentLeft.setAddTime(DateUtil.date());
		commentLeft.setUpdTime(commentLeft.getAddTime());
		orderCommentLeftMapper.insertSelective(commentLeft);
	}

	@Override
	@Transactional(propagation=Propagation.REQUIRED, rollbackFor=Exception.class)
	public void deleteLeftComment(Integer leftCommentId) {
		orderCommentLeftMapper.deleteByPrimaryKey(leftCommentId);
	}

	@Override
	@Transactional(propagation=Propagation.REQUIRED, rollbackFor=Exception.class)
	public void continuteAddComment(UmsMember member, OrderCommentForm form) throws ServiceException {
		// 通过订单详情id获取当前订单对应的评论后作为父级评论id
//		QueryWrapper<TyOrderComment> commentQueryWrapper = new QueryWrapper<>();
//		commentQueryWrapper.eq("order_id",form.getId());
//		TyOrderComment comment = orderCommentMapper.selectOne(commentQueryWrapper);
//		if (!Optional.ofNullable(comment).isPresent()){
//			log.error("【托运追评失败】被追加的评论不存在");
//			throw new ServiceException("追评失败");
//		}

//		TyOrderComment comment = orderCommentMapper.selectByPrimaryKey(form.getId());

//		if(comment.getStatus() != OrderEnums.CommentStatus.COMMENTED.getValue()){
//			throw new ServiceException("order.comment.continute.add");
//		}




		TyOrder order;
		if(form.getId() != null){
			order  = orderMapper.selectByPrimaryKey(form.getId());
		}else{
			throw new ServiceException("order.comment.add");
		}

		if(order == null || order.getCommentStatus() != OrderEnums.CommentStatus.COMMENTED.getValue()){
			throw new ServiceException("order.comment.add");
		}




		TyOrderComment updateComment = new TyOrderComment();
		updateComment.setOrderId(form.getId());
//		updateComment.setType("ty");
		updateComment.setMemberId(order.getMemberId());
		updateComment.setMemberName(member.getNickname());
		updateComment.setMemberHeadImg(member.getHeadImg());


		updateComment.setAnonymousStatus(form.getAnonymousStatus());
		updateComment.setContent(form.getContent());
		updateComment.setImg(form.getImg());
		updateComment.setGoodsComment(form.getGoodsComment());
		updateComment.setGoodsStarNum(form.getGoodsStarNum());
		updateComment.setDeliveryStarNum(form.getDeliveryStarNum());
		updateComment.setShopStarNum(form.getShopStarNum());
		updateComment.setLogisticStarNum(form.getLogisticStarNum());
		updateComment.setAvgStarNum(NumberUtil.div(NumberUtil.add(form.getGoodsStarNum(), form.getDeliveryStarNum(), form.getShopStarNum(),form.getLogisticStarNum()), 4));
		updateComment.setStatus(OrderEnums.CommentStatus.COMMENTED.getValue());
		updateComment.setUpdTime(DateUtil.date());
		orderCommentMapper.insertSelective(updateComment);

		//更新订单详情页面的评价状态
		TyOrder updateDetail = new TyOrder();
		updateDetail.setId(form.getId());
		updateDetail.setCommentStatus(2);
		orderMapper.updateByPrimaryKeySelective(updateDetail);


//		TyOrderComment updateComment = new TyOrderComment();
//		updateComment.setId(comment.getId());
//		updateComment.setStatus(OrderEnums.CommentStatus.ADD_COMMENTED.getValue());
//		orderCommentMapper.updateByPrimaryKeySelective(updateComment);
	}
}
